package com.web.rate.service;

import com.alibaba.fastjson.JSONObject;
import com.web.common.BaseResult;
import com.web.common.enums.BaseStatus;
import com.web.currency.entity.Currency;
import com.web.rate.entity.Rate;
import com.web.rate.mapper.RateMapper;
import com.web.systemParam.entity.SystemParam;
import com.web.transaction.entity.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RateService {

	public static final String DEF_CHATSET = "UTF-8";
	public static final int DEF_CONN_TIMEOUT = 30000;
	public static final int DEF_READ_TIMEOUT = 30000;
	public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

	//配置申请的APPKEY
	public static final String APPKEY ="56098381a2ef361ca60c86ab7c57a527";

	@Resource
    private RateMapper mapper;

	private static final Logger logger = LoggerFactory.getLogger(RateService.class);


	public List<Rate> getRates(Rate r) {
		return mapper.getRates(r);
	}

	public Rate getRate(String currency, String buySell) {
		return mapper.getRate(currency, buySell);
	}

	public BaseResult checkAcceptedRate(BigDecimal costRate, BigDecimal acceptedBooKRate, SystemParam systemParam) {

		BigDecimal costRateToler = new BigDecimal(systemParam.getSystemParamValue()).divide(new BigDecimal("100")).setScale(5, RoundingMode.HALF_DOWN);

		BigDecimal baseDecimal = BigDecimal.ONE;

		BigDecimal maxAcceptedRate = baseDecimal.add(costRateToler).multiply(costRate);


		logger.info("costRateToler: {}, maxAcceptedRate: {},acceptedBooKRate: {}",costRateToler,maxAcceptedRate,acceptedBooKRate);
		if(acceptedBooKRate.compareTo(maxAcceptedRate) > 0 || acceptedBooKRate.compareTo(costRate) < 0){
			return new BaseResult<>(BaseStatus.INVALID_BOOK_RATE.getCode(),BaseStatus.INVALID_BOOK_RATE.getDesc());
		}

		return new BaseResult<>(BaseStatus.SUCCESS.getCode(),acceptedBooKRate);
	}


	public Integer getLatestRate(JSONObject json){

		List<Rate> rates = new ArrayList<>();

		for (int i = 0; i <json.size() ; i++) {
			if (i == 1){
				continue;
			}
			int serialNumber = i + 1;
			JSONObject rJsonDate1 = (JSONObject) json.get("data"+serialNumber);
			BigDecimal buyRate = rJsonDate1.getBigDecimal("buyPic");
			BigDecimal sellRate = rJsonDate1.getBigDecimal("sellPic");
			String currency = rJsonDate1.getString("code");
			rates = createRate(buyRate, sellRate, currency,rates);
		}

		//更新DB中的Rate
		Integer updateResult = updateLatestRate(rates);

		return updateResult;
	}

	private static List<Rate> createRate(BigDecimal buyRate, BigDecimal sellRate, String currency,List<Rate> rates){
		//如果是USD vs XXX形式的货币
		if (currency.startsWith(Currency.USD)) {
			currency =  currency.substring(currency.length() - 3);
		}else {
			currency =  currency.substring(0, 3);
		}

		Rate rateBuy = new Rate();
		Rate rateSell = new Rate();

		rateBuy.setBuySell(Transaction.TX_BUY);
		rateBuy.setRate(buyRate);
		rateBuy.setCurrency(currency);

		rateSell.setBuySell(Transaction.TX_SELL);
		rateSell.setRate(sellRate);
		rateSell.setCurrency(currency);

		rates.add(rateBuy);
		rates.add(rateSell);

		return rates;
	}

	private Integer updateLatestRate(List<Rate> rates){

		return mapper.updateRate(rates);
	}

	/**
	 *
	 * @param strUrl 请求地址
	 * @param params 请求参数
	 * @param method 请求方法
	 * @return  网络请求字符串
	 * @throws Exception
	 */
	public static String net(String strUrl, Map params,String method) throws Exception {
		HttpURLConnection conn = null;
		BufferedReader reader = null;
		String rs = null;
		try {
			StringBuffer sb = new StringBuffer();
			if(method==null || method.equals("GET")){
				strUrl = strUrl+"?"+urlencode(params);
			}
			URL url = new URL(strUrl);
			conn = (HttpURLConnection) url.openConnection();
			if(method==null || method.equals("GET")){
				conn.setRequestMethod("GET");
			}else{
				conn.setRequestMethod("POST");
				conn.setDoOutput(true);
			}
			conn.setRequestProperty("User-agent", userAgent);
			conn.setUseCaches(false);
			conn.setConnectTimeout(DEF_CONN_TIMEOUT);
			conn.setReadTimeout(DEF_READ_TIMEOUT);
			conn.setInstanceFollowRedirects(false);
			conn.connect();
			if (params!= null && method.equals("POST")) {
				try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
					out.writeBytes(urlencode(params));
				}
			}
			InputStream is = conn.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sb.append(strRead);
			}
			rs = sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (conn != null) {
				conn.disconnect();
			}
		}
		return rs;
	}

	//将map型转为请求参数型
	public static String urlencode(Map<String,Object>data) {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry i : data.entrySet()) {
			try {
				sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
